package com.seecen.utils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

/**
 * FIND YOUR PURPOSE
 *
 * @author: CYZ
 * @date: 2025/10/20/18:44
 * @description:
 */
public class CaptchaUtil {

    // 验证码字符集（数字和大写字母）
    private static final String CHAR_SET = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    private static final int WIDTH = 90;   // 验证码图片宽度
    private static final int HEIGHT = 40; // 验证码图片高度
    private static final int FONT_SIZE = 20; // 字体大小
    private static final Random RANDOM = new Random();

    /**
     * 生成指定长度的验证码
     * @param length 验证码长度
     * @return 验证码字符串
     */
    public static String generateCaptcha(int length) {
        StringBuilder captcha = new StringBuilder();
        for (int i = 0; i < length; i++) {
            captcha.append(CHAR_SET.charAt(RANDOM.nextInt(CHAR_SET.length())));
        }
        return captcha.toString();
    }

    /**
     * 生成验证码图片
     * @param captcha 验证码字符串
     * @param outputStream 输出流
     * @throws IOException IO异常
     */
    public static void generateCaptchaImage(String captcha, OutputStream outputStream) throws IOException {
        // 创建图片
        BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = image.createGraphics();

        // 设置背景色
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, WIDTH, HEIGHT);

        // 设置字体
        g.setFont(new Font("Arial", Font.BOLD, FONT_SIZE));

        // 绘制验证码字符
        for (int i = 0; i < captcha.length(); i++) {
            // 设置随机颜色
            g.setColor(new Color(RANDOM.nextInt(150), RANDOM.nextInt(150), RANDOM.nextInt(150)));

            // 计算字符位置
            int x = (i * (WIDTH / captcha.length())) + 5;
            int y = HEIGHT - 10;

            // 绘制字符
            g.drawString(String.valueOf(captcha.charAt(i)), x, y);
        }

        // 添加干扰线
        for (int i = 0; i < 5; i++) {
            g.setColor(new Color(RANDOM.nextInt(255), RANDOM.nextInt(255), RANDOM.nextInt(255)));
            int x1 = RANDOM.nextInt(WIDTH);
            int y1 = RANDOM.nextInt(HEIGHT);
            int x2 = RANDOM.nextInt(WIDTH);
            int y2 = RANDOM.nextInt(HEIGHT);
            g.drawLine(x1, y1, x2, y2);
        }

        // 添加干扰点
        for (int i = 0; i < 30; i++) {
            g.setColor(new Color(RANDOM.nextInt(255), RANDOM.nextInt(255), RANDOM.nextInt(255)));
            int x = RANDOM.nextInt(WIDTH);
            int y = RANDOM.nextInt(HEIGHT);
            g.drawOval(x, y, 1, 1);
        }

        g.dispose();

        // 输出图片
        ImageIO.write(image, "png", outputStream);
        outputStream.close();
    }
}